package com.winning.pmph.ctrl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.OperationLog;
import com.winning.pmph.entity.User;
import com.winning.pmph.service.OperationLogService;
import com.winning.pmph.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(value = "系统管理/日志审计")
@RestController
@RequestMapping("/pmph/action/operationLog")
public class OperationLogCtrl {
    @Resource
    OperationLogService operationLogService;

    @Resource
    private UserService userService;

    @ApiOperation(value = "selectOperationLog", notes = "查询审计日志列表")
    @PostMapping("selectOperationLog")
    public Page<OperationLog> selectOperationLog(@RequestBody OperationLog operationLog) {
        // 查询所有用户
        Map<Integer, List<String>> userMap = userService.lambdaQuery().list().stream()
                .collect(Collectors.groupingBy(User::getKind, Collectors.mapping(User::getUserName, Collectors.toList())));
        LambdaQueryChainWrapper<OperationLog> query = operationLogService.lambdaQuery().eq(StringUtils.isNotBlank(operationLog.getUserName()), OperationLog::getUserName, operationLog.getUserName())
                .like(StringUtils.isNotBlank(operationLog.getModules()), OperationLog::getModules, operationLog.getModules())
                .eq(StringUtils.isNotBlank(operationLog.getEventResult()), OperationLog::getEventResult, operationLog.getEventResult())
                .like(StringUtils.isNotBlank(operationLog.getIp()), OperationLog::getIp, operationLog.getIp())
                .in(Objects.nonNull(operationLog.getUserType()), OperationLog::getUserName, userMap.get(operationLog.getUserType()))
                .orderByDesc(OperationLog::getCreatedTime)
                .orderByAsc(OperationLog::getId);
        if (CollectionUtils.isNotEmpty(operationLog.getTimeRange())) {
            query.between(OperationLog::getCreatedTime, operationLog.getTimeRange().get(0), operationLog.getTimeRange().get(1));
        }
        Page<OperationLog> page = query.page(new Page<>(operationLog.getCurrentPage(), operationLog.getPageSize()));
        return page;
    }

    @ApiOperation(value = "selectLogById", notes = "根据id查询日志")
    @GetMapping("selectLogById")
    public OperationLog selectLogById(String id) {
        return operationLogService.getById(id);
    }
}
